# -*- coding: utf-8 -*-
import hashlib
import json
import time
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '1169_001': {
        #  汇付通支付 支付宝 2.5% 10-20000 dwc
        'API_KEY': '5q45o5j2xni9oy8y7ymbun02nu8bwmgb',
        'CALL_BACK_KEY': '6ccmwg6ropggighg4tthrfh94gzepxyy',
        'gateway': 'http://47.107.242.216/pay/api/api.php?action=pay&m=pay_it',
        'query_gateway': 'http://47.107.242.216/pay/api/api.php?action=pay&m=get_order_info',
    },
    '8888_002': {
        #  汇付通支付 支付宝 2.5% 10-20000 witch
        'API_KEY': '9wmp7wja5r4bs7d0r9xy0o3pd5fxpueq',
        'CALL_BACK_KEY': '4frketeai9ua3ciyuvpheo8yltf7ndqv',
        'gateway': 'http://47.107.242.216/pay/api/api.php?action=pay&m=pay_it',
        'query_gateway': 'http://47.107.242.216/pay/api/api.php?action=pay&m=get_order_info',
    },
    '8888_003': {
        #  汇付通支付 支付宝 2.5% 10-20000 loki
        'API_KEY': 'jwc8zcb9ps5mr94mqinyosmvlu1n0rbg',
        'CALL_BACK_KEY': '8jayfaix717bvsh7vquag7q35irptykc',
        'gateway': 'http://47.107.242.216/pay/api/api.php?action=pay&m=pay_it',
        'query_gateway': 'http://47.107.242.216/pay/api/api.php?action=pay&m=get_order_info',
    },
    '8888_001': {
        #  汇付通支付 支付宝 2.5% 10-20000 tt
        'API_KEY': 'qli3rdr3emkuzraxort8wal55uttpdcg',
        'CALL_BACK_KEY': 'w08wc53g4dt9fcjddtk1wym3o8m5717s',
        'gateway': 'http://47.107.242.216/pay/api/api.php?action=pay&m=pay_it',
        'query_gateway': 'http://47.107.242.216/pay/api/api.php?action=pay&m=get_order_info',
    },
    '8888_004': {
        #  汇付通支付 支付宝 2.5% 10-20000 dwc
        'API_KEY': '31w0m0ja4outdirxr5s8c95m7u5ds343',
        'CALL_BACK_KEY': 'n6ho2x2qq9pyz2zwddfng5l1k2oi3phw',
        'gateway': 'http://47.107.242.216/pay/api/api.php?action=pay&m=pay_it',
        'query_gateway': 'http://47.107.242.216/pay/api/api.php?action=pay&m=get_order_info',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_call_back_key(mch_id):
    return APP_CONF[mch_id]['CALL_BACK_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _build_create_string(params):
    s = '&partner_no={}&mch_order_no={}&body={}&money={}&time_stamp={}&token={}&code_type={}&callback_url={}'.format(
        params['partner_no'], params['mch_order_no'],
        params['body'], params['money'], params['time_stamp'], params['token'], params['code_type'],
        params['callback_url']
    )
    return s


def _build_query_string(params):
    s = '&partner_no={}&order_no={}&time_stamp={}&token={}'.format(
        params['partner_no'], params['order_no'],
        params['time_stamp'], params['token']
    )
    return s


def generate_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().lower()
    return sign


def gen_order_sign(d, key):
    s = 'mch_order_no={}&money={}&partner_no={}&time_stamp={}&key={}'.format(
        d['mch_order_no'], d['money'], d['partner_no'], d['time_stamp'], key
    )
    return generate_sign(s)


def gen_verify_sign(d, key):
    s = 'mch_order_no={}&money={}&order_no={}&time_stamp={}&key={}'.format(
        d['mch_order_no'], d['money'], d['order_no'], d['time_stamp'], key
    )
    return generate_sign(s)


def gen_query_sign(d, key):
    s = 'order_no={}&partner_no={}&time_stamp={}&key={}'.format(
        d['order_no'], d['partner_no'], d['time_stamp'], key
    )
    return generate_sign(s)


def verify_notify_sign(params, key):
    sign = params['token']
    params.pop('token')
    calculated_sign = gen_verify_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("huifutongpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_pay_type(service):
    if service == 'alipay':
        return '2'
    elif service == 'wechat':
        return '1'
    return '2'


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('partner_no', app_id),
        ('mch_order_no', str(pay.id)),
        ('body', 'HuiFuTongPay'),
        ('money', str(int(pay_amount * 100))),
        ('callback_url', '{}/pay/api/{}/huifutongpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('time_stamp', int(round(time.time() * 1000))),
        ('code_type', _get_pay_type(service)),
    ))
    parameter_dict['token'] = gen_order_sign(parameter_dict, api_key)
    _LOGGER.info("huifutongpay create: %s, order_id is: %s", json.dumps(parameter_dict), parameter_dict['mch_order_no'])
    url = _get_gateway(app_id) + _build_create_string(parameter_dict)
    _LOGGER.info("huifutongpay create url: %s", url)
    response = requests.get(url, timeout=3)
    _LOGGER.info("huifutongpay data response: %s", response.text)
    return {'charge_info': json.loads(response.text)['code_link']}


# success
def check_notify_sign(request, app_id):
    call_back_key = _get_call_back_key(app_id)
    data = dict(request.GET.iteritems())
    _LOGGER.info("huifutongpay notify data: %s, order_id is: %s", data, data['mch_order_no'])
    verify_notify_sign(data, call_back_key)
    pay_id = data['mch_order_no']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s", data)
        raise ParamError('huifutongpay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['code'])
    trade_no = data['order_no']
    total_fee = float(data['money']) / 100.0
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    check_channel_order(pay_id, total_fee, app_id)
    # 0:成功
    if trade_status == '0':
        _LOGGER.info('huifutongpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    # prepare param
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('partner_no', app_id),
        ('order_no', pay_order.third_id),
        ('time_stamp', int(round(time.time() * 1000))),
    ))
    parameter_dict['token'] = gen_query_sign(parameter_dict, api_key)
    _LOGGER.info("huifutongpay query data: %s", json.dumps(parameter_dict))
    url = _get_query_gateway(app_id) + _build_query_string(parameter_dict)
    _LOGGER.info("huifutongpay query url: %s", url)
    response = requests.get(url, timeout=3)
    _LOGGER.info("huifutongpay query rsp data: %s, order_id is: %s", response.text,
                 json.loads(response.text)['data']['mch_order_no'])
    if response.status_code == 200:
        data = json.loads(response.text)
        trade_status = str(data['code'])
        trade_no = str(data['data']['order_no'])
        total_fee = float(data['data']['money_real']) / 100.0

        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }

        if trade_status == '0':
            _LOGGER.info('huifutongpay query order success, user_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('huifutongpay data error, status_code: %s', response.status_code)
